﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;

namespace WayProbe.Percussion
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("Input a url to post, or just type enter to terminate:");
                var line = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(line))
                {
                    break;
                }
                else
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(line);
                    RequestState state = new RequestState();
                    state.request = request;
                    var result = request.BeginGetResponse(RequestBack, state);
                    ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, Properties.Settings.Default.StethocopeTimeout, true);
                    allDone.WaitOne();
                    state.response.Close();
                }
            }
        }

        static ManualResetEvent allDone = new ManualResetEvent(false);

        static void RequestBack(IAsyncResult ar)
        {
            var response = (ar.AsyncState as HttpWebRequest).EndGetResponse(ar);
            //todo: read response
            allDone.Set();
        }

        static void TimeoutCallback(object state, bool timedOut)
        {
            if (timedOut)
            {
                HttpWebRequest request = state as HttpWebRequest;
                if (request != null)
                {
                    request.Abort();
                }
            }
        }
    }
}
